<?php

namespace Helper\Controller;

//use Think\Image;
use Think\Upload;
use OSS\OssClient;
use OSS\OssException;
//use OSS\Core\OssUtil;
//use Util\StringUtils;
use Common\Controller\ApiController;
//use vod\Request\V20170321\CreateUploadVideoRequest;
//use Aliyun\Core\Config;
//use Aliyun\Core\Profile\DefaultProfile;
//use Aliyun\Core\DefaultAcsClient;
//use Biz\AliyunMedia;
//use Biz\AliyunVod;
use Ruben\Aliyun\Oss;
use Ruben\Aliyun\StsServer;

class UploadController extends ApiController {

    public function newoss() {
        $config = C('sdk.oss');
        $ossClient = new OssClient($config['access_key_id'], $config['access_key_secret'], $config['endpoint']);
        return $ossClient;
    }

    public function webuploader() {
        header('Access-Control-Allow-Methods:OPTIONS');
        header('Access-Control-Allow-Headers:Content-Type, Access-Control-Allow-Headers, Authorization');
        header('Access-Control-Allow-Origin:*');
        exit;
        // $this->ajaxReturn(['success' => true]);
    }

    /**
     * 上传图片
     */
    public function uploadImage() {
        header('Access-Control-Allow-Origin:*');
        $input = $this->request();
        $type = filter($input['type'], 'images');
        $config = $this->getConfig('oss_image');
        $driverConfig = C('sdk.oss');
        $upload = new Upload($config, 'Oss', $driverConfig);
        $fileinfos = $upload->upload();
        $urls = [];
        if ($fileinfos) {
            foreach ($fileinfos as $fileinfo) {
                if (isset($driverConfig['cdn'])) {
                    $osshost = "http://" . $driverConfig['bucket'] . '.' . $driverConfig['endpoint'];
                    $fileinfo['url'] = str_replace($osshost, $driverConfig['cdn'], $fileinfo['url']);
                }
                $urls['images'][] = $fileinfo['url'];
            }
            echo json_encode($urls);
        } else {
            $this->errorResponse(20001, $upload->getError());
        }
    }

    /**
     * 授权上传
     */
    public function prepareUpload() {
        $config = C('sdk.oss');
        $oss = new Oss($config);
        $info = $oss->prepareUpload();
        dump($info);
    }

    public function getStsToken() {
        $config = C('sdk.oss-ram');
        $sts = new StsServer($config);
        $token = $sts->getStsToken();
        $token = json_decode($token, true);
        $token['endpoint'] = $config['endpoint'];
        $token['bucket'] = $config['bucket'];
        $this->response($token);
    }

    public function uploadMicroVideo() {
        ini_set("max_execution_time", 1800);
        if (!isset($_FILES['video'])) {
            $this->errorResponse(20002);
        }
        $type = 'microvideos';
        $config = $this->getConfig($type);
        $driverConfig = C('sdk.oss');
        $upload = new Upload($config, 'Oss', $driverConfig);
        $fileinfo = $upload->uploadOne($_FILES['video']);
        if ($fileinfo) {
            //获取封面
//            $mts = new Mts($driverConfig);
//            $mediaInfo = $mts->queryMediaListByURL($fileinfo['url']);
//            $media = $mediaInfo->MediaList->Media;
//            $cover_url = 0;
//             if (count($media)) {
//                    $cover_url = $media[0]->CoverURL;
//                }
//            D('Media')->add(['url'=>$fileinfo['url']]);
            
            if (isset($driverConfig['cdn'])) {
                $osshost = "http://" . $driverConfig['bucket'] . '.' . $driverConfig['endpoint'];
                $fileinfo['url'] = str_replace($osshost, $driverConfig['cdn'], $fileinfo['url']);
            }
            
            $this->createdResponse(['video' => $fileinfo['url']]);
        } else {
            $this->errorResponse(10019, '只能上传50M及以下的mp4格式视频');
        }
    }

    private function getConfig($type) {
        switch ($type) {
            case 'oss_image':
                return [
                    'maxSize' => 1024 * 1024 * 10,
                    'rootPath' => 'images',
                    'savePath' => date('Ymd'),
                    'saveName' => ['uuid'],
                    'exts' => ['jpg', 'gif', 'png', 'jpeg', 'webp', 'bmp'],
                    'autoSub' => false,
                ];
            case 'microvideos':
                return [
                    'maxSize' => 1024 * 1024 * 100,
                    'rootPath' => 'artvideos',
                    'savePath' => '',
                    'saveName' => ['uuid'],
                    'exts' => ['mp4'],
                    'autoSub' => false,
                ];
            case 'image':
                return [
                    'maxSize' => 1024 * 1024 * 3,
                    'rootPath' => './Uploads/',
                    'savePath' => date('Ymd') . '/',
                    'saveName' => ['uniqid', ''],
                    'exts' => ['jpg', 'gif', 'png', 'jpeg'],
                    'autoSub' => false,
                ];
            case 'video':
                return [
                    'maxSize' => 1024 * 1024 * 5,
                    'rootPath' => './Uploads/',
                    'savePath' => date('Ymd') . '/',
                    'saveName' => ['uniqid', ''],
                    'exts' => ['mp3', 'amr'],
                    'autoSub' => false,
                ];
            case 'video':
                return [
                    'maxSize' => 1024 * 1024 * 600,
                    'rootPath' => './Uploads/',
                    'savePath' => date('Ymd') . '/',
                    'saveName' => ['uniqid', ''],
                    'exts' => ['mp4', 'rmvb'],
                    'autoSub' => false,
                ];
            default:
                return [
                    'maxSize' => 1024 * 2,
                    'rootPath' => './Uploads/',
                    'savePath' => date('Ymd') . '/',
                    'saveName' => ['uniqid', ''],
                    'autoSub' => false,
                ];
        }
    }

    /*
     * 删除图片
     */

    public function deleteImage() {
        $config = C('sdk.oss');
        $input = $this->request();
        try {
            $ossClient = $this->newoss();
            $delete = $this->isExistImages($input);
            if (count($delete) > 1) {
                $ossClient->deleteObjects($config['bucket'], $delete);
            } else {
                $ossClient->deleteObject($config['bucket'], $delete[0]);
            }
            $this->createdResponse();
        } catch (OssException $e) {
            
        }
    }

    private function isExistImages($delete) {
        $config = C('sdk.oss');
        $ossClient = $this->newoss();
        try {
            $res = $ossClient->doesBucketExist($config['bucket']);
            if (!$res) {
                $this->errorResponse(10001, 'oss bucket 不存在');
            }
            $deleteArr = explode(',', $delete['objectname']);
            foreach ($deleteArr as $value) {
                $imageName = $this->getObjectName($value);
                $exist = $ossClient->doesObjectExist($config['bucket'], $imageName);
                if ($exist) {
                    $images[] = $imageName;
                }
            }
        } catch (OssException $e) {
            
        }
        return $images;
    }

    private function getObjectName($value) {
        $imageArr = explode('/', $value, 4);
        return $imageArr[count($imageArr) - 1];
    }

}
